﻿using MyServer.Common;
using MyServer.Udp;
using ScreenMonitor.Common;
using ScreenMonitor.Common.Objects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace ScreenMonitor.ClientLib
{
    public static class UdpCommandOperator
    {
        
        #region========私有变量========

        private static object LockObj = new object();
        private static object SendLockObj = new object();

        #endregion

        public static bool RunCommand(DataPackageCollection pkg)
        {
            lock (LockObj)
            {
                try
                {
                    string command = Util.GetCommandLine(pkg.PackageName);
                    switch (command)
                    {
                        case CommandType.ServerStarted:
                            return DoServerStarted(pkg);
                        case CommandType.AcceptConnect:
                            return DoAcceptConnect(pkg);
                        default:
                            return false;
                    }
                }
                catch
                {
#if DEBUG
                throw;
#else
                    return false;
#endif
                }
            }
        }

        private static bool DoServerStarted(DataPackageCollection pkg)
        {
            UdpPkgInfo info=(UdpPkgInfo)pkg.Tag;
            CommandObjects.UdpCommandCenter.SendCommand(CommandType.ClientStarted, info.BindPoint);
            return true;
        }

        private static bool DoAcceptConnect(DataPackageCollection pkg)
        {
            UdpPkgInfo info = (UdpPkgInfo)pkg.Tag;
            AcceptConnectObject obj=AcceptConnectObject.FromByte(DataPacker.UnPackData(pkg));
            ClientTask.BitmapSize = new System.Drawing.Size(obj.ScreenViewImgWidth, obj.ScreenViewImgHeight);
            ClientTask.BitMapFormat = obj.ImageType;
            ClientTask.SendBitmapRate = obj.SendImgRate;
            ClientTask.IsAutoStartSendImg = obj.IsAutoStartSendImg;
            ClientTask.SendBitmapSizeMode = obj.SendImgSizeMode;
            ServerObject.ClientBase =new TcpClient(info.BindPoint.Address.ToString(), obj.ServerTcpPort);
            ServerObject.Connect();
            return true;
        }


    }
}
